package Dijkstra;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import roborally.Board;
import roborally.Direction;
import roborally.Position;
import Exceptions.IllegalCoordinateException;

/**
 * @author Jef Keijers/Bachelor of Science: Informatics
 * @version 1.0
 */

public class DijkstraPath implements Comparable<DijkstraPath> {
	
	public DijkstraPath(List<Position> positionList) {
		this.positionList = Collections.unmodifiableList(copyList(positionList)); // enkel leesbaar :) niet wijzigbaar ^^
	}
	
	public List<Position> getPositionList() {
		return positionList;	
	}
	
	public Position getLastPosition() {
		return positionList.get(positionList.size()-1);
	}
	
	private List <Position> positionList;
	
	
	public boolean hasReached(Position pos) {
		return getLastPosition().equals(pos);
	}

	public Collection<DijkstraPath> extendPath(Board board) {
		ArrayList<DijkstraPath> paths = new ArrayList<DijkstraPath>();		
		extendPathInDirection(paths, Direction.UP, board);
		extendPathInDirection(paths, Direction.DOWN, board);
		extendPathInDirection(paths, Direction.RIGHT, board);
		extendPathInDirection(paths, Direction.LEFT, board);	
		
		return paths;
	}
	
	private void extendPathInDirection(ArrayList<DijkstraPath> paths, Direction direction,Board board) {
		try {
			List <Position> extendedPath = copyList(getPositionList());
			Position p=getLastPosition(); // position die je moet uitbreiden  ... :)
			p = p.move(direction, board);
			if ( extendedPath.contains(p))
				return;
			extendedPath.add(p);
			paths.add(new DijkstraPath(extendedPath));
		} catch (IllegalCoordinateException exc) {
			// NOP
		}
		
	}
	
	private ArrayList <Position> copyList(List <Position> list) {
		ArrayList<Position> copy=new ArrayList<Position>();
		copy.addAll(list);
		return copy;
	}

	@Override
	public int compareTo(DijkstraPath o) {
		return this.getPositionList().size()-o.getPositionList().size();
	}
}
